﻿var zombies = zombies || {};

zombies.ListAdmin = function () {
    var self = this;
    self.Admins = ko.observableArray();
    self.SearchString = ko.observable("");
    self.CurrentPage = ko.observable(1);
    self.IsPrevious = ko.observable(false);
    self.IsNext = ko.observable(false);
    self.Loaded = ko.observable(false);

    self.SendMsg = function (data, event) {
        try {
            if (event.which === 13) {
                self.CurrentPage(1);
                load(self.CurrentPage(), self.SearchString());
                $.replaceUrl(self.CurrentPage(), self.SearchString());
                return false;
            }
            return true;
        }
        catch (e)
        { }

    };

    self.AdId = ko.observable();
    self.UserId = ko.observable();
    self.UserName = ko.observable();
    self.Email = ko.observable();
    self.CreateDate = ko.observable();
    self.ImgUrl = ko.observable();


    self.AdminData = ko.observable({
        AdId: self.AdId,
        UserId: self.UserId,
        UserName: self.UserName,
        Email: self.Email,
        CreateDate: self.CreateDate,
        ImgUrl: self.ImgUrl
    });

    self.itemTodel = ko.observable();

    self.getEditItem = function (item) {
        self.AdId(item.AdId);
        self.UserId(item.UserId);
        self.UserName(item.UserName);
        self.Email(item.Email);
        self.CreateDate(item.CreateDate);
        self.ImgUrl(item.ImgUrl);
    }
    self.doEdit = function (formElement) {
        var admin = ko.utils.arrayFirst(self.Admins(), function (item) {
            return item.AdId === self.AdId();
        })
        if ($(formElement).valid()) {
            $.ajax({
                type: "PUT",
                url: "/api/AdminManagement/PutAdmin",
                data: ko.toJSON(self.AdminData), //Convert the Observable Data into JSON
                contentType: "application/json",
                dataType: 'json'
            }).done(function () {
                toastr.success('Edit Admin Successfully !');
                self.Admins.replace(admin, { AdId: self.AdId(), UserId: self.UserId(), UserName: self.UserName(), Email: self.Email(), CreateDate: self.CreateDate(), ImgUrl: self.ImgUrl() });
                $('#pro-edit').modal('hide');
            }).fail(function () {
                toastr.error('Edit Admin Failed !');
            });
        }
    }

    self.doDelete = function (item) {
        $.confirm({
            text: "Are you very sure to delete admin " + item.UserName + " ?",
            confirm: function (button) {
                $.ajax({
                    type: "DELETE",
                    url: "/api/AdminManagement/DeleteAdmin/" + item.AdId,
                    success: function (data) {
                        self.Admins.remove(item);
                        toastr.success("Delete Admin Successfully !");
                    },
                    error: function (error) {
                        toastr.error("Delete Admin Failed !");
                    }
                });
            },
            confirmButton: "Yes",
            cancelButton: "No"
        });
    }

    self.doNext = function () {
        if (self.IsNext()) {
            var page = self.CurrentPage();
            page++;
            self.CurrentPage(page);
            load(page, self.SearchString);
            if (page == 1) {
                self.IsPrevious(false)
            } else {
                self.IsPrevious(true);
            }
            $.replaceUrl(page, self.SearchString());
            App.scrollTo($('#pro-list'), -100);
        }
    }

    self.doPrevious = function () {
        if (self.IsPrevious()) {
            var page = self.CurrentPage() - 1;
            self.CurrentPage(page);
            load(page, self.SearchString);
            if (page == 1) {
                self.IsPrevious(false)
            } else {
                self.IsPrevious(true);
            }
            $.replaceUrl(page, self.SearchString());
            App.scrollTo($('#pro-list'), -100);
        }
    }
}

var load = function (id, searchString) {
    viewModel.Loaded(false);
    viewModel.Admins.removeAll();
    $.ajax({
        url: '/api/AdminManagement/GetAdmins/' + id,
        type: 'GET',
        data: { value: searchString },
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        if (items.length === 11) {
            items.pop();
            viewModel.IsNext(true);
        } else {
            viewModel.IsNext(false);
        }
        $.each(items, function (idx, item) {
            viewModel.Admins.push(new zombies.Admin(item));
        });
        viewModel.Loaded(true);
    }).error(function () {
        toastr.error('Lỗi');
    })
};

ko.bindingHandlers.fileUpload = {
    init: function (element, valueAccessor) {
        $(element).after('<div class="progress" style="display: none; width: 50%"><div class="bar"></div><div class="percent">0%</div></div><div class="progressError"></div>');
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var options = ko.utils.unwrapObservable(valueAccessor()),
            property = ko.utils.unwrapObservable(options.property),
            url = ko.utils.unwrapObservable(options.url);

        if (property && url) {
            $(element.form).change(function () {
                if (element.files.length)
                    viewModel.IconPath("../Advertise/AdminImg/" + $('#upload').prop("files")[0].name);
            });
            $(element.form).submit(function () {
                if ($(element.form).valid() && element.files.length) {
                    var $this = $(element),
                        filename = $this.val();
                    // this uses jquery.form.js plugin
                    $(element.form).ajaxSubmit({
                        url: url,
                        type: "POST",
                        dataType: "json",
                        headers: { "Content-Disposition": "attachment; filename=" + filename },
                        beforeSubmit: function () {
                            $(".progress").show();
                            $(".progressError").hide();
                            $(".bar").width("0%")
                            $(".percent").html("0%");
                        },
                        uploadProgress: function (event, position, total, percentComplete) {
                            var percentVal = percentComplete + "%";
                            $(".bar").width(percentVal)
                            $(".percent").html(percentVal);
                        },
                        success: function (data) {
                            $(".progress").hide();
                            $(".progressError").hide();
                            // set viewModel property to IconPath
                            bindingContext.$data[property](data);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            $(".progress").hide();
                            $("div.progressError").html(jqXHR.responseText);
                        }
                    });
                }
            });
        }
    }
}


var viewModel;
$(document).ready(function () {

    viewModel = new zombies.ListAdmin();

    ko.applyBindings(viewModel, document.getElementById("admin_content"));

    var pageUrl = $.getUrlVars("page");
    var searchStringUrl = $.getUrlVars("searchString");
    if (typeof pageUrl === 'undefined' || !isFinite(String(pageUrl))) {
        viewModel.CurrentPage(1);
    } else {
        viewModel.CurrentPage(pageUrl);
    }
    if (typeof searchStringUrl === 'undefined') {
        viewModel.SearchString("");
    } else {
        viewModel.SearchString(searchStringUrl);
    }
    if (pageUrl > 1) viewModel.IsPrevious(true);
    load(viewModel.CurrentPage(), viewModel.SearchString());
});
